<template>
  <!-- 这是收货地址管理 -->
  <div id="addressManagement">
    <h3>{{$t("addressManagement.title")}}</h3>
    <div :class="['Shipping_address']" v-for="(address, index) in receivingInformation" :key="address.id">
      <div><h4>{{address.realname}}</h4></div>
      <div>{{address.mobile}}</div>
      <div class="middle">{{address.province}} {{address.city}} {{address.area}}</div>
      <div>{{address.address}}</div>
      <div class="operation">
        <span>{{$t("addressManagement.default")}} </span>
        <el-switch v-model="address.isdefault" :active-value='1' :inactive-value='0' @change='changeSwitch(address,index)' :width='35' inactive-color="#ccc"></el-switch>
        <span class="modifyNone" @click.stop="changeAddress(index)">{{$t("addressManagement.edit")}}</span>
        <span class="delete" @click.stop="del(index)">{{$t("addressManagement.delete")}}</span>
      </div>
    </div>
    <div class="Shipping_address" @click="AddNewAddress">
      <div class="Add_shipping_address">
        <i class="el-icon-circle-plus"></i>
        <div><span>{{$t("Transport.newAddress")}}</span></div>
      </div>
    </div>
    <!-- 修改收货地址弹框 -->
    <el-dialog
      :title="modifySA_title"
      @close="SAVCloseCallback"
      :visible.sync="SAVisible"
      width="40%">
      <el-form :model="ruleForm" :rules="rules" label-position="top" ref="ruleForm" label-width="100px">
        <el-form-item prop="name" class="Shipping_address_name">
            <el-input v-model.trim="ruleForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item prop="phone" class="Receiving_mobile_number">
            <el-input v-model.trim="ruleForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item prop="desc">
          <!-- 地区选择器 -->
          <v-distpicker :province="ruleForm.province" :city="ruleForm.city" :area="ruleForm.area" @selected="selected"></v-distpicker>
          <el-input class="disInput" type="textarea" resize='none' :rows="2" v-model="ruleForm.desc" placeholder="请输入详细地址"></el-input>
          
        </el-form-item>
      </el-form>
      <span>设为默认地址 </span>
      <el-switch v-model="switchValue" :width='35' inactive-color="#ccc"></el-switch>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SAVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSAVisible">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import VDistpicker from 'v-distpicker';
export default {
  data () {
    return {
      receivingInformation: [],   // 收货地址
      switchValue: false,  // 是否设为默认地址
      modifySA_title: '',   // 修改或者新增，弹框标题
      SAVisible: false, // 是否打开收货地址弹框
      ruleForm: {
        index: '',
        name: '', 
        phone: '',
        desc: ''  ,//详细地址
        province: '',   //省份
        city: '',   //城市
        area: '',   //地区
        addressID: '',  //选择收货地址的id
        isdefault: '',  //是否设为默认地址
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { pattern: /^[a-zA-Z\u4e00-\u9fa5]{2,15}$/, message: '姓名只能字母或者中文，2-15字符',trigger: 'blur'}
        ],
        phone: [
          { required: true, message: '请输入11位手机号码', trigger: 'blur' },
          { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: '手机号码不正确！',trigger: 'blur'}
        ],
        desc: [
          { required: true, message: '请填写详细地址', trigger: 'blur' }
        ]
      },
    }
  },
  components: {
    VDistpicker
  },
  methods: {
    // 添加收货地址
    AddNewAddress() {
      this.SAVisible = true;
      this.switchValue = false;
      this.modifySA_title = "添加收货地址";
    },
    // 编辑收货地址
    changeAddress(index) {
      var _this = this;
      this.SAVisible = true;
      this.modifySA_title = "修改收货地址";
      if(this.receivingInformation[index].isdefault == '1') {
        // for(let i = 0; i < _this.receivingInformation.length; i++) {
        //   _this.receivingInformation[i].isdefault = '0';
        // }
        // _this.receivingInformation[index].isdefault = '1';
        _this.switchValue = true;
        _this.ruleForm.isdefault = '1';
      } else {
        // for(let i = 0; i < _this.receivingInformation.length; i++) {
        //   _this.receivingInformation[i].isdefault = '0';
        // }
        _this.switchValue = false;
        _this.ruleForm.isdefault = '0';
      }
      _this.ruleForm.index = JSON.stringify(index);  // 收货地址数组，下标
      _this.ruleForm.name = _this.receivingInformation[index].realname;  //姓名
      _this.ruleForm.phone = _this.receivingInformation[index].mobile;  // 手机号码
      _this.ruleForm.desc = _this.receivingInformation[index].address;  //详细地址

      _this.ruleForm.province = _this.receivingInformation[index].province; //省
      _this.ruleForm.city = _this.receivingInformation[index].city; //市
      _this.ruleForm.area = _this.receivingInformation[index].area; //区
    },
    // 删除收货地址
    del(index) {
      var _this = this;
      _this.$confirm('此操作将删除该数据, 是否继续?'
      ).then(() => {
        _this.$dele(`user/address/${_this.$Cookie.getCookie('userID')}/${_this.receivingInformation[index].id}`
        ).then(res =>{
          if(res.code == 204) {
            _this.$MessageAlert(true, "删除成功", 'success');
            _this.receivingInformation.splice(index, 1);
          }
        })
        
        // _this.$MessageAlert(true, "删除成功", 'success');

        // if(_this.receivingInformation.length > 2) {
        //   _this.EARendering = true;
        // } else {
        //   _this.EARendering = false;
        // }
      }).catch(() => {
        _this.$MessageAlert(true, "已经取消删除", 'success');
      });
    },
    // 默认地址change事件
    changeSwitch(data, index) {
      var _this = this;
      _this.$post('user/address/default',{
        openid: _this.$Cookie.getCookie('userID'),
        id: data.id,
      }).then(res=>{
        if(res.code == 201) {
          for (let i = 0; i < _this.receivingInformation.length; i++) {
            if(index != i) {
              _this.receivingInformation[i].isdefault = 0;
            }
          }
        }
      }).catch(()=>{
        _this.receivingInformation[index].isdefault = 0;
        // _this.SAVisible = false;
      })
    },
    // 收货地址框的关闭回调
    SAVCloseCallback() {
      this.$refs['ruleForm'].resetFields();
      this.ruleForm.index = '';  //index，下标
      this.ruleForm.name = '';   //姓名
      this.ruleForm.phone = '';  // 手机号码
      this.ruleForm.desc = '';   //详细地址
      this.ruleForm.province = '';  //省
      this.ruleForm.city = '';  //市
      this.ruleForm.area = '';  //区
    },
    // 地区选择器
    selected(data) {
      var _this = this;
      _this.ruleForm.province = data.province.value;
      _this.ruleForm.city = data.city.value;
      _this.ruleForm.area = data.area.value;
    },
    // 获取收货地址
    getAddress() {
      var _this = this;
      _this.$get(`user/address/${_this.$Cookie.getCookie('userID')}`).then(res=>{
        if(res.code == 200) {
          _this.receivingInformation = res.data;
          // for(let i = 0; i < _this.receivingInformation.length; i++) {
          //   // 判断，把默认收货地址id，赋值
          //   if(_this.receivingInformation[i].isdefault == '1') {
          //     _this.ruleForm.addressID = _this.receivingInformation[i].id;
          //   }
          // }
          // 判断收货地址是否大于2，决定是否显示，更多收货地址栏
          // if(_this.receivingInformation.length > 2) {
          //   _this.EARendering = true;
          // } else {
          //   _this.EARendering = false;
          // }
        } 
      })
    },
    // 确定，修改或者添加收货地址
    confirmSAVisible() {
      var _this = this;
      _this.$refs['ruleForm'].validate((valid) => {
        if(valid) {
          let num = Number(_this.ruleForm.index);
          let modifyName = _this.ruleForm.name.replace(/\s*/g,"");
          let modifyPhone = _this.ruleForm.phone.replace(/\s*/g,"");
          let modifyProvince = _this.ruleForm.province.replace(/\s*/g,"");
          let modifyCity = _this.ruleForm.city.replace(/\s*/g,"");
          let modifyArea = _this.ruleForm.area.replace(/\s*/g,"");
          let modifyDesc = _this.ruleForm.desc.replace(/\s*/g,"");

          // let modifyIsdefault = _this.ruleForm.isdefault;
          if(_this.ruleForm.index != '') {
            // 修改
            // 要是弹框的默认地址是true，把数组全部地址isdefault改为0，
            if(_this.switchValue) {
              // for(let i = 0; i < _this.receivingInformation.length; i++) {
              //   _this.receivingInformation[i].isdefault = '0';
              // }
              _this.ruleForm.isdefault = '1';
            } else {
              _this.ruleForm.isdefault = '0';
            }
            if(_this.ruleForm.area.length > 1) {

              // _this.receivingInformation[num].isdefault
              if(_this.receivingInformation[num].realname.replace(/\s*/g,"") != modifyName || _this.receivingInformation[num].mobile.replace(/\s*/g,"") != modifyPhone || _this.receivingInformation[num].province.replace(/\s*/g,"") != modifyProvince || _this.receivingInformation[num].city.replace(/\s*/g,"") != modifyCity || _this.receivingInformation[num].area.replace(/\s*/g,"") != modifyArea || _this.receivingInformation[num].address.replace(/\s*/g,"") != modifyDesc || _this.receivingInformation[num].isdefault != _this.ruleForm.isdefault) {
                // 修改收货地址，接口
                _this.$put(`user/address/${_this.$Cookie.getCookie('userID')}/${_this.receivingInformation[num].id}`,{
                  realname: _this.ruleForm.name,
                  mobile: _this.ruleForm.phone,
                  province: _this.ruleForm.province,
                  city: _this.ruleForm.city,
                  area: _this.ruleForm.area,
                  address: _this.ruleForm.desc,
                  isdefault: _this.ruleForm.isdefault,
                  zipcode: '',
                }).then(res=>{
                  if(res.code == 201) {
                    _this.ruleForm.index = '';
                    for(let i = 0; i < _this.receivingInformation.length; i++) {
                      _this.receivingInformation[i].isdefault = '0';
                    };
                    _this.receivingInformation[num].realname = _this.ruleForm.name;
                    _this.receivingInformation[num].mobile = _this.ruleForm.phone;
                    _this.receivingInformation[num].province = _this.ruleForm.province;
                    _this.receivingInformation[num].city = _this.ruleForm.city;
                    _this.receivingInformation[num].area = _this.ruleForm.area;
                    _this.receivingInformation[num].address = _this.ruleForm.desc;
                    _this.receivingInformation[num].isdefault = Number(_this.ruleForm.isdefault);

                    _this.SAVisible = false;
                  } else {
                    // _this.$MessageAlert(true, res.data, 'error')
                    _this.SAVisible = false;
                  }
                }).catch(()=>{
                  _this.SAVisible = false;
                })
              } else {
                _this.SAVisible = false;
                _this.$MessageAlert(true, '地址相同，不进行修改', 'success')
              }
            } else {
              _this.$MessageAlert(true, '请选择地区', 'error')
            }
            
          } else {
            // 添加
            let obj = {};
            if(_this.switchValue) {
              obj.isdefault = '1';
            } else {
              obj.isdefault = '0';
            }
            // 判断地区，是否为空
            if(_this.ruleForm.area !== "" && _this.ruleForm.area !== "区") {
              // 添加收货地址，接口
              _this.$post('user/address', {
                openid: _this.$Cookie.getCookie('userID'),
                realname: _this.ruleForm.name,
                mobile: _this.ruleForm.phone,
                province: _this.ruleForm.province,
                city: _this.ruleForm.city,
                area: _this.ruleForm.area,
                address: _this.ruleForm.desc,
                isdefault: obj.isdefault,
                zipcode: ''
              }).then(res=>{
                if(res.code == 201) {
                  // 获取收货地址
                  _this.getAddress();
                } 
                _this.SAVisible = false;
              }).catch(()=>{
                _this.SAVisible = false;
              })
            } else {
              _this.$MessageAlert(true, "请选择地区", "error");
            }
            
          }
        }
      })
      
    },
  },
  created () {
    var _this = this;
    _this.getAddress();   // 获取收货地址
  }
}
</script>

<style lang='less' scoped>
#addressManagement {
  h3 {
    text-transform: none;
    color: #333;
    margin-top: 20px;
    margin-bottom: 10px;
  }
}

.Shipping_address {
  color: #646262;
  margin: 15px 0px;
  padding: 15px 25px 0px;
  display: inline-block;
  border: 1px solid #ccc;
  width: 320px;
  margin-right: 100px;
  height: 180px;
  vertical-align: middle;
  cursor: pointer;
  position: relative;
  div {
    font-size: 13px;
    font-weight: 100;
    h4 {
      color: #646262;
      margin: 10px 0px;
      text-transform: none;
    }
  }
  .middle {
    margin: 3px 0px;
  }
  
  .operation {
    position: relative;
    margin-top: 25px;
    .modifyNone {
      margin: 0px;
      font-size: 14px;
      // color: #ff6700;
      position: absolute;
      bottom: 0px;
      right: 53px;
    }
    .delete {
      position: absolute;
      bottom: 0px;
      right: 5px;
      font-size: 14px;
    }
  }
}
.Shipping_address:hover {
    border-color: #ff6700;
    .el-icon-circle-plus {
      color: #b0b0b0;
      transition-duration: 0.3s;
    }
  }
.Shipping_address:nth-child(odd) {
  margin-right: 0px;
}
.Add_shipping_address {
  margin-top: 39px;
  text-align: center;
  .el-icon-circle-plus {
    color: #e0e0e0;
    font-size: 32px;
    margin-bottom: 7px;
    transition-duration: 0.3s;
  }
  div {
    color: #b0b0b0;
    span {
      font-size: 16px;
    }
  }
}
/deep/ .el-switch__core{
  height:17px;
}
/*设置圆*/
/deep/ .el-switch__core::after{
  width:15px;
  height:15px;
  margin-top:-1px;
  margin-bottom: 2px;
}
// 地区选择器
/deep/ .distpicker-address-wrapper select {
  font-size: 1.3rem;
}
// .el-icon-circle-plus {
//   color: #ff6700;
//   margin-right: 5px;
//   vertical-align: middle;
//   font-size: 24px;
// }
/deep/ .el-dialog {
  max-width: 600px;
  min-width: 500px;
}
.Shipping_address_name {
  width: 47%;
  display: inline-block;
  vertical-align: middle;
}
.Receiving_mobile_number {
  width: 47%;
  display: inline-block;
  vertical-align: middle;
  margin-left: 6%;
}
.disInput {
  margin-top: 25px;
  margin-left: 0px !important;
  // border: 1px !important;
}
</style>